import { useEffect, useState } from "react";
import { projectAPI } from "../../apis/project";
import { Button, Form, Input, Modal, Space, Table } from "antd";
import { fmtDateTime } from "../../utils";
import modStl from "../user/user-list.mod.less";
import { PlusOutlined, ReloadOutlined } from "@ant-design/icons";
import ProjectForm from "./common/project-form";

interface ProjectRecordType {
  title: string;
  dataIndex?: string;
  key: string;
  render?: any;
  ellipsis?: boolean;
  width?: number|string;
  colSpan?: number;
}

const actions = {
  "add": 'add',
  "del": 'del',
  "edit": "edit"
}

const ProjectListPage = () => {
  const [page, setPage] = useState({
    pageIndex: 1,
    pageSize: 10,
    total: 0
  })
  const [tableData, setTableData] = useState([]);
  const [searchData, setSearchData] = useState({
    searchKey: ''
  });
  const [loading, setLoading] = useState(false);
  const [curAction, setCurAction] = useState('');
  const [isEditVisible, setIsEditVisible] = useState(false);
  const [isModalLoading, setIsModalLoading] = useState(false);
  const [userItem, setProjectItem] = useState(null);

  const columns: ProjectRecordType[] = [
    {
      title: "ID",
      dataIndex: "id",
      key: 'id',
      width: 60
    },
    {
      title: "名称",
      dataIndex: "name",
      key: 'name',
      ellipsis: true,
    },
    {
      title: "平台",
      dataIndex: "platform",
      key: 'platform',
      ellipsis: true,
    },
    {
      title: "域名",
      dataIndex: "app_host",
      key: 'app_host',
      ellipsis: true,
    },
    {
      title: "密钥",
      dataIndex: "app_secret",
      key: 'app_secret',
      ellipsis: true
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      ellipsis: true,
      render: (t: string) => {
        return <span>{fmtDateTime(t)}</span>
      }
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: '10%',
      render: (text: string, record: any) => (
        <Space size="small">
          <Button type="link" size={"small"} onClick={() => btnHandler(actions.edit, record)}>
            编辑
          </Button>
          <Button type="link" size={"small"} onClick={() => showDelConfirm(record)}>删除</Button>
        </Space>
      )
    }
  ]

  useEffect(getTableData, [page.pageIndex, searchData.searchKey]);

  function getTableData() {
    setLoading(true);
    projectAPI.projectList({
      pageIndex: page.pageIndex,
      pageSize: page.pageSize,
      ...searchData,
    }).then((res: any) => {
      if (res && res.success) {
        setTableData(res.data.list)
        setPage({
          ...page,
          total: res.data.pageInfo.total
        });
      }
    }).finally(() => {
      setLoading(false)
    })
  }

  function btnHandler (action: string, row?: any) {
    setCurAction(action);
    switch (action) {
      case actions.add:
        setIsEditVisible(true);
        break;
      case actions.edit:
        setIsEditVisible(true);
        setProjectItem(row);
        break;
    }
  }

  /**
   * @desc 删除用户
   * @author Gaollard
   * @param record
   */
  function showDelConfirm(record: any) {
    Modal.confirm({
      title: '确认删除吗？',
      content: `应用 ${record.name} 等被删除后将无法恢复`,
      onOk() {
        return projectAPI.projectDel({
          id: record.id
        }).then((res: any) => {
          if (res && res.success) {
            getTableData();
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();

  const onFinishTableForm = (values: any) => {
    setSearchData(values);
  }

  function okEditModal() {
    form.submit();
  }

  /**
   * 取消时, 需要清除脏状态
   */
  function cancelEditModal() {
    setIsEditVisible(false);
    setProjectItem(null);
    form.resetFields();
  }

  return (
    <>
      <div className={modStl['table-toolbar']}>
        {/*搜索表单*/}
        <Form form={searchForm} onFinish={onFinishTableForm} name="sForm" layout={"inline"}>
          <Form.Item name="searchKey">
            <Input placeholder={"用户帐号"} allowClear={true} value={searchData.searchKey}/>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" >
              查询
            </Button>
          </Form.Item>
        </Form>
        {/*右侧工具栏*/}
        <Space size={"large"}>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => btnHandler(actions.add)}>
            新建
          </Button>
          <Space size={"middle"}>
            <a className="ui-hover-text" onClick={e => e.preventDefault()}>
              <ReloadOutlined onClick={getTableData}/>
            </a>
          </Space>
        </Space>
      </div>



      <Table
        rowKey={"id"}
        bordered
        columns={columns}
        size={"middle"}
        loading={loading}
        dataSource={ tableData }
        pagination={{
          showQuickJumper: false,
          showTotal: () => `共 ${ page.total } 条`,
          pageSize: page.pageSize,
          total: page.total,
          current: page.pageIndex,
          onChange: (v) => setPage({ ...page, pageIndex: v}),
        }}
      />

      <Modal
        title={ curAction === actions.add ? "添加应用" : "编辑应用" }
        width={ 500 }
        visible={ isEditVisible }
        onOk={ okEditModal }
        onCancel={ cancelEditModal }
        okButtonProps={ {loading: isModalLoading} }
      >
        <ProjectForm
          form={ form }
          setSubmitLoading={ setIsModalLoading }
          onSubmitSuccess={ () => {
            setProjectItem(null);
            setIsEditVisible(false);
            page.pageIndex !== 1 ? setPage({
              ...page,
              pageIndex: 1
            }) : getTableData()
          } }
          isEdit={ Boolean(userItem) }
          formInfo={ userItem }
        />
      </Modal>
    </>
  )
}

export default ProjectListPage;